package com.atguigu.day03;

import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
                .fromElements(1,2,3,4).setParallelism(1)
                .keyBy(r -> r % 2)
                .print("keyBy: ").setParallelism(2);

        env
                .fromElements(1,2,3,4).setParallelism(1)
                .partitionCustom(
                        // 指定将某个key的数据发送到哪一个物理分区
                        new Partitioner<Integer>() {
                            @Override
                            public int partition(Integer key, int numPartitions) {
                                // 参数key是下面的KeySelector指定的key
                                // 将key为1的发送到下游的第2个分区
                                // 将key为0的发送到下游的第3个分区
                                // 返回值是数据要发送到的下游的物理分区的索引
                                return key == 1 ? 2 : 3;
                            }
                        },
                        // 为每个数指定key
                        // 每来一条数据就指定一个key，那么这条数据发送到下游的哪一个物理分区呢？
                        new KeySelector<Integer, Integer>() {
                            @Override
                            public Integer getKey(Integer value) throws Exception {
                                // 按照奇偶性来逻辑分区
                                return value % 2;
                            }
                        }
                )
                .print("自定义物理分区：").setParallelism(4);

        env.execute();
    }
}
